/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.yxw.yxnet_cd_center.customer_service.utils;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.File;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.BufferedOutputStream;
/**
 *
 * @author Administrator
 */
public class HttpUtils {
    public static void download(HttpServletResponse Response,String FilePath)
    {
        Response.reset();
        java.io.File oFile = new java.io.File(FilePath);        
        if(!oFile.exists())
        {
            System.out.println("File not exsist");
            return;// BaseResult.failed("File not exsist");
        }
        if(!oFile.isFile())
        {
            System.out.println(oFile.getName() + " is not a file");
            return;// BaseResult.failed(FileName + " is not a file");
        }        
        
        Response.addHeader("Pragma", "No-Cache");
        Response.addHeader("Cache-Control", "No-Cache");//application/octet-stream
        Response.setContentType("application/octet-stream");
        //Response.setDateHeader("Expires", 0);
        //if(FilePath.toLowerCase().endsWith(".txt"))
        //{
        //    Response.setHeader("Content-Type","text/plain");
        //    Response.setHeader("charset","utf-8");
        //}
        try
        {
            Response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(oFile.getName(), "UTF-8"));
            // 告知浏览器文件的大小
            Response.addHeader("Content-Length", "" + oFile.length());
        }
        catch(UnsupportedEncodingException oE)
        {
            System.out.println("exportProcessInOnePlan Exception:" + oE.getMessage());
            return;// BaseResult.failed("Download Exception:" + oE.getMessage());
        } 
        ServletOutputStream oServletOutputStream = null;
        FileInputStream oFileInputStream = null;
        try
        {           
            
            oFileInputStream = new FileInputStream(FilePath); // 读入文件
            oServletOutputStream = Response.getOutputStream();
            //oServletOutputStream.flush();
            int aRead = 0;
            while ((aRead = oFileInputStream.read()) != -1 & oFileInputStream != null) {
                oServletOutputStream.write(aRead);
            }
        }
        catch(IOException oE)
        {
            System.out.println("Download Exception:" + oE.getMessage());
            return;// BaseResult.failed("Download Exception:" + oE.getMessage());
        } 
        finally
        {
            try
            {  
                oFileInputStream.close();
                //oServletOutputStream.close();
            }
            catch(IOException oE)
            {
                System.out.println("Download Exception:" + oE.getMessage());
                return;// BaseResult.failed("Download Exception:" + oE.getMessage());
            }
            try
            { 
                oServletOutputStream.close();
            }
            catch(IOException oE)
            {
                System.out.println("Download Exception:" + oE.getMessage());
                return;// BaseResult.failed("Download Exception:" + oE.getMessage());
            }           
        }
        System.out.println("Download ok");
        //return;// BaseResult.success("Download ok");
    }
    /**
     * @param path     想要下载的文件的路径
     * @param response
     * @功能描述 下载文件:
     */
    public static void downloadComplit(String path, HttpServletResponse response)
    {
        File oFile = new File(path);
        if(!oFile.exists())
        {
            System.out.println("File not exsist");
            return;// BaseResult.failed("File not exsist");
        }
        if(!oFile.isFile())
        {
            System.out.println(path + " is not a file");
            return;// BaseResult.failed(FileName + " is not a file");
        }              
        //log.info(file.getPath());
        // 清空response
        response.reset();    
        FileInputStream fileInputStream = null;
        InputStream fis = null;
        OutputStream outputStream = null;
        try 
        {
            // 获取文件后缀名
            //String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            //log.info("文件后缀名：" + ext);
            // 将文件写入输入流
            fileInputStream = new FileInputStream(oFile);
            fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(oFile.getName(), "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + oFile.length());
            outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
        } 
        catch (IOException ex) 
        {
            ex.printStackTrace();
            System.out.println("DownloadComplit Exception:" + ex.getMessage());
        }
        finally
        {
            try
            {           
                fis.close();
                //oServletOutputStream.close();
            }
            catch(IOException oE)
            {
                System.out.println("DownloadComplit Exception:" + oE.getMessage());
                return;// BaseResult.failed("Download Exception:" + oE.getMessage());
            }
            try
            {           
                outputStream.close();
                //oServletOutputStream.close();
            }
            catch(IOException oE)
            {
                System.out.println("DownloadComplit Exception:" + oE.getMessage());
                return;// BaseResult.failed("Download Exception:" + oE.getMessage());
            }             
        }        
    }
    
}
